import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:speed_random/app_styles.dart';
import 'package:speed_random/core/config/app_config.dart';
import 'package:speed_random/core/services/ad_service.dart';
import 'package:speed_random/pages/home/home.dart';


class IndexPage extends StatefulWidget {
  IndexPage({Key? key}) : super(key: key);


  @override
  _IndexPageState createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage> with WidgetsBindingObserver {

  bool _isAppInBackground = false; // 添加应用是否在后台的标志
  Widget? _bannerAdWidget;
  bool _isLoaded = false;
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this); // 添加生命周期监听
    AppConfig.current.adService.showAd(adType: AdType.banner,onAdLoadedBanner: (ad){
      _bannerAdWidget=ad;
      setState(() {
        _isLoaded = true;
      });
    },forceShow: true);

  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this); // 移除生命周期监听
    super.dispose();
  }


  // 添加生命周期状态监听
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.paused) {
      _isAppInBackground = true;
    } else if (state == AppLifecycleState.resumed && _isAppInBackground) {
      _isAppInBackground = false;
     Future.delayed(Duration(seconds: 3), () {
       // 展示开屏广告
       AppConfig.current.adService.showAd(adType: AdType.appOpen);
     });

    }
  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Expanded(
            child: Home(),
          ),
          if (_isLoaded)_bannerAdWidget!,
        ],
      ),
    /*  bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        onTap: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
        backgroundColor: Colors.white,
        selectedItemColor: Colors.blueAccent,
        unselectedItemColor: Colors.black54,
        unselectedLabelStyle: TextStyle(color: Colors.black54),
        type: BottomNavigationBarType.fixed,
        items:  [
          BottomNavigationBarItem(icon: Icon(Icons.home), label: "首页".tr),
          BottomNavigationBarItem(icon: Icon(Icons.abc), label: '解梦'.tr),
          BottomNavigationBarItem(icon: Icon(Icons.local_florist), label: '幸运'.tr),
          BottomNavigationBarItem(icon: Icon(Icons.search), label: '搜寻'.tr),
          BottomNavigationBarItem(icon: Icon(Icons.person), label: '我的'.tr),
        ],
      ),*/
    );
  }
}